#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h> 

#define SERVER_IP "192.168.1.101"
#define SERVER_PORT    5555


int main(int argc, char **argv)
{
    int client_fd;

    client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(0 > client_fd) {
        perror("socket error");
        exit(-1);
    }

    struct sockaddr_in server_addr = {0}; 
    char buf[512]; 

    //调用connect连接远端服务器 
    server_addr.sin_family = AF_INET; 
    server_addr.sin_port = htons(SERVER_PORT);  //端口号 
    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);//服务器设备的IP地址

    if(0 > connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr))) {
        perror("connect error"); 
        close(client_fd); 
        exit(-1);
    }

    printf("服务器连接成功...\n\n"); 

    for ( ; ; ) { 
        // 清理缓冲区 
        memset(buf, 0x0, sizeof(buf)); 
 
        // 接收用户输入的字符串数据 
        printf("Please enter a string: "); 
        fgets(buf, sizeof(buf), stdin); 
 
        // 将用户输入的数据发送给服务器 
        if(0 > send(client_fd, buf, strlen(buf), 0)){ 
            perror("send error"); 
            break; 
        } 
 
        //输入了"exit"，退出循环 
        if(0 == strncmp(buf, "exit", 4)) 
            break; 
    }

    close(client_fd);
    exit(0);
}